package com.google.code.pokerstats_service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

import javax.servlet.http.*;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@SuppressWarnings("serial")
public class Pokerstats_serviceServlet extends HttpServlet {
    public Pokerstats_serviceServlet() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        gson = gsonBuilder.create();
    }
    
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebServiceParams params;
        
        BufferedReader br = req.getReader();
        try {
            String line = br.readLine();
            params = gson.fromJson(line, WebServiceParams.class);
        } finally {
            br.close();
        }
        
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("utf-8");
        PrintWriter writer = resp.getWriter();

        if (params.method == null) {
            writer.print("error: no method specified for POST.");
            
        } else if (params.method.equals("getStats")) {
            GetStatsParams getStatsParams =
                gson.fromJson(params.jsonObj, GetStatsParams.class);
            Set<PlayerStats> playersStats = pss.getStats(getStatsParams);
            writer.print(gson.toJson(playersStats));
            
        } else if (params.method.equals("getGames")) {
            Long groupId = gson.fromJson(params.jsonObj, Long.class);
            Set<Game> games = pss.getGames(groupId);
            writer.print(gson.toJson(games));

        } else if (params.method.equals("getResults")) {
            Long gameId = gson.fromJson(params.jsonObj, Long.class);
            Set<PlayerResult> results = pss.getPlayerResults(gameId);
            writer.print(gson.toJson(results));
            
        } else if (params.method.equals("postGame")) {
            Game game = gson.fromJson(params.jsonObj, Game.class);
            pss.postGame(game);
            writer.print(gson.toJson(game.id));
            
        } else if (params.method.equals("postResult")) {
            PlayerResult playerResult =
                gson.fromJson(params.jsonObj, PlayerResult.class);
            pss.postPlayerResult(playerResult);
            writer.print(gson.toJson(playerResult.id));
            
        } else {
            writer.print("error: invalid POST method (" + params.method + ").");
        }
    }
    
    private final PokerStatsService pss = new PokerStatsService();
    private final Gson gson;
}